//package com.javasm.config;
//
//import com.alibaba.fastjson.JSONObject;
//import com.javasm.service.LoginUserService;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.security.config.annotation.web.builders.HttpSecurity;
//import org.springframework.security.config.annotation.web.builders.WebSecurity;
//import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
//import org.springframework.security.core.Authentication;
//import org.springframework.security.core.AuthenticationException;
//import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
//import org.springframework.security.crypto.password.PasswordEncoder;
//import org.springframework.security.web.AuthenticationEntryPoint;
//import org.springframework.security.web.authentication.AuthenticationFailureHandler;
//import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
//import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
//import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
//
//import javax.servlet.ServletException;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import javax.sql.DataSource;
//import java.io.IOException;
//import java.io.PrintWriter;
//import java.util.HashMap;
//import java.util.Map;
//
////
//@Configuration
//public class SecurityConfig extends WebSecurityConfigurerAdapter {
//    /**
//     * 声明一个 PasswordEncoder ，
//     *      在 userservice 中注入使用
//     *      同时 spring security 自动使用这个解密
//     * 这样数据库存储的密码就不需要 "{加密方式}"，这样的前缀
//     * @return
//     */
//    @Bean
//    public PasswordEncoder passwordEncoder(){
//        return new BCryptPasswordEncoder();
//    }
//    @Override
//    public void configure(WebSecurity web) throws Exception {
//        // 静态资源不用验证
//        web.ignoring().antMatchers("/js/**", "/css/**","/images/**");
//    }
//    @Override
//    protected void configure(HttpSecurity http) throws Exception {
//        http.authorizeRequests()
//                .antMatchers("/fail.html").permitAll()
//                .anyRequest().authenticated()
//                .and()
//                .formLogin()
//                .loginProcessingUrl("/user/login")
//                .usernameParameter("name")
//                .passwordParameter("pass")
//                // 登录成功后设置json格式的返回结果
//                .successHandler(new AuthenticationSuccessHandler() {
//                    /**
//                     *
//                     * @param request
//                     * @param response
//                     * @param authentication 保存了登录成功的用户信息
//                     * @throws IOException
//                     */
//                    @Override
//                    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
//                                                        Authentication authentication) throws IOException {
//                        response.setContentType("application/json;charset=utf-8");
//                        PrintWriter out = response.getWriter();
//                        out.write(JSONObject.toJSONString(authentication));
//                        out.flush();
//                        out.close();
//                    }
//                })
//                // 登录失败后设置json格式的返回结果
//                .failureHandler(new AuthenticationFailureHandler() {
//                    @Override
//                    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
//                                                        AuthenticationException exception) throws IOException, ServletException {
//                        response.setContentType("application/json;charset=utf-8");
//                        PrintWriter out = response.getWriter();
//                        Map<String,String> map = new HashMap<>();
//                        map.put("errMsg", exception.getMessage());
//                        out.write(JSONObject.toJSONString(map));
//                        out.flush();
//                        out.close();
//                    }
//                })
//                .permitAll()
//                .and()
//                .csrf().disable();//关闭 csrf，后面讨论
//
//        http.exceptionHandling().authenticationEntryPoint(new AuthenticationEntryPoint() {
//            @Override
//            public void commence(HttpServletRequest request, HttpServletResponse response,
//                                 AuthenticationException authException) throws IOException, ServletException {
//                response.setContentType("application/json;charset=utf-8");
//                PrintWriter out = response.getWriter();
//                Map<String,String> map = new HashMap<>();
//                map.put("errMsg", "尚未登录，请先登录");
//                out.write(JSONObject.toJSONString(map));
//                out.flush();
//                out.close();
//            }
//        });
//        http.logout().logoutUrl("/user/logout")
//                .logoutSuccessHandler(new LogoutSuccessHandler() {
//                    @Override
//                    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
//                        response.setContentType("application/json;charset=utf-8");
//                        PrintWriter out = response.getWriter();
//                        out.write("退出成功");
//                        out.flush();
//                        out.close();
//                    }
//                });
//        //configure 方法 增加
//        http.rememberMe()
//                .tokenRepository(jdbcTokenRepositoryImpl()) // 配置token持久化仓库
//                // .tokenValiditySeconds(3600) // 过期时间，单位为秒
//                .userDetailsService(loginUserService); // 处理自动登录逻辑
//    }
//    @Autowired
//    private LoginUserService loginUserService;
//    @Autowired
//    private DataSource dataSource;//javax.sql.DataSource包下的类
//    /**
//     * remember me 功能是基于token验证的，
//     * 这里是通过JdbcTokenRepositoryImpl把token存到persistent_logins表中
//     * @return
//     */
//    @Bean
//    public JdbcTokenRepositoryImpl jdbcTokenRepositoryImpl() {
//        JdbcTokenRepositoryImpl persistentTokenRepository = new JdbcTokenRepositoryImpl();
//        persistentTokenRepository.setDataSource(dataSource);
//        return persistentTokenRepository;
//    }
//
//}